// 2025/11/13
// 二叉树展开为链表

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        if(!root) return;
        stack<TreeNode*> st;
        st.emplace(root);
        TreeNode head, *cur = &head;
        while(!st.empty())
        {
            cur->right = st.top();
            st.pop();
            cur = cur->right;
            if(cur->right)
                st.emplace(cur->right);
            if(cur->left)
                st.emplace(cur->left);
            cur->left = nullptr;
        }
    }
};